package com.top.ruizhong.popup

import android.content.Context
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.TextView
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ToastUtils
import com.jakewharton.rxbinding2.widget.RxTextView
import com.top.ruizhong.R
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Function3
import kotlinx.android.synthetic.main.popup_password_setting.view.*
import razerdp.basepopup.BasePopupWindow
import java.util.concurrent.TimeUnit

class PasswordSettingPopup(
    context: Context,
    val onGetCode: (phone: String) -> Unit,
    val onConfirm: (smsCode: String, password: String, confirmPassword: String) -> Unit
) : BasePopupWindow(context) {

    init {
        setOverlayNavigationBar(false)
        setAdjustInputMethod(false)
    }


    override fun onCreateContentView(): View {
        return createPopupById(R.layout.popup_password_setting)
    }

    override fun onViewCreated(contentView: View) {
        super.onViewCreated(contentView)
        BarUtils.addMarginTopEqualStatusBarHeight(contentView.flPwdSettingBar)
        val observableCode: Observable<CharSequence> =
            RxTextView.textChanges(contentView.etPwdSettingCodeVerify)
        val observablePwd: Observable<CharSequence> =
            RxTextView.textChanges(contentView.etPwdSettingPassword)
        val observablePwdSure: Observable<CharSequence> =
            RxTextView.textChanges(contentView.etPwdSettingPasswordSure)
        val disposable: Disposable = Observable.combineLatest(
            observableCode, observablePwd, observablePwdSure,
            Function3<CharSequence, CharSequence, CharSequence, Boolean> { t1, t2, t3 ->
                t1.isNotEmpty() && t2.isNotEmpty() && t3.isNotEmpty()
            })
            .subscribe {
                contentView.tvPwdSettingConfirm.isEnabled = it
            }
        contentView.tvPwdSettingCodeGet.setOnClickListener {
            val phone: String? = contentView.tvPwdSettingPhone.text.toString()
            if (phone.isNullOrEmpty()) {
                ToastUtils.showShort("手机号为空！请检查相关代码！")
            } else {
                onGetCode(phone)
            }
        }
        contentView.tvPwdSettingConfirm.setOnClickListener {
            val smsCode: String = contentView.etPwdSettingCodeVerify.text.toString()
            val password: String = contentView.etPwdSettingPassword.text.toString()
            val confirmPassword: String = contentView.etPwdSettingPasswordSure.text.toString()
            when {
                password.length != 6 -> ToastUtils.showShort("请输入6位数字密码！")
                password != confirmPassword -> ToastUtils.showShort("确认密码错误！")
                else -> onConfirm(smsCode, password, confirmPassword)
            }
        }
    }

    override fun onCreateShowAnimation(width: Int, height: Int): Animation {
        return TranslateAnimation(
            Animation.RELATIVE_TO_PARENT, 0f,
            Animation.RELATIVE_TO_PARENT, 0f,
            Animation.RELATIVE_TO_PARENT, 1f,
            Animation.RELATIVE_TO_PARENT, 0f
        ).apply { duration = 300L }
    }

    override fun onCreateDismissAnimation(): Animation {
        return TranslateAnimation(
            Animation.RELATIVE_TO_PARENT, 0f,
            Animation.RELATIVE_TO_PARENT, 0f,
            Animation.RELATIVE_TO_PARENT, 0f,
            Animation.RELATIVE_TO_PARENT, 1f
        ).apply { duration = 300L }
    }

    fun setTitle(title: String): PasswordSettingPopup {
        contentView.tvPwdSettingTitle.text = title
        return this
    }

    fun setPhone(phone: String?): PasswordSettingPopup {
        contentView.tvPwdSettingPhone.text = phone
        return this
    }

    private val dispose: CompositeDisposable = CompositeDisposable()

    /**
     * 获取验证码倒计时
     * */
    fun startCodeDownTime() {
        val disposable: Disposable = Flowable.intervalRange((1), (60), (0), (1), TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext {
                contentView.tvPwdSettingCodeGet.text = "剩余${60 - it}秒"
            }
            .doOnSubscribe {
                contentView.tvPwdSettingCodeGet.isEnabled = false
            }
            .doOnComplete {
                contentView.tvPwdSettingCodeGet.let {
                    it.text = "获取验证码"
                    it.isEnabled = true
                }
            }
            .subscribe()
        dispose.add(disposable)
    }

    fun stopCodeDownTime() {
        dispose.clear()
    }

    override fun showPopupWindow() {
        super.showPopupWindow()
        contentView.etPwdSettingCodeVerify.text = null
        contentView.etPwdSettingPassword.text = null
        contentView.etPwdSettingPasswordSure.text = null
        contentView.tvPwdSettingCodeGet.let {
            it.text = "获取验证码"
            it.isEnabled = true
        }
    }

    override fun dismiss() {
        super.dismiss()
        stopCodeDownTime()
    }

}